<script setup>
import {useRoute} from "vue-router";
import {stateOptions} from "@/mixins/index.js";
import {useUserStore} from "@/store/index.js";
import {apiParam, fieldVisible} from "@/utils/index.js";
import {induce} from "@/utils/derive.js";
import {changeDateFormat, getNowDate} from "@/utils/time.js";
import {skyNoticeSuccess, skyNoticeError, skyMsgError, skyMsgWarning, skyMsgBox, skyMsgInfo, skyMsgSuccess} from "@/utils/sky.js";
import {productTypeApi} from "@/apis/PLM/frmProductType/index.js";

const route = useRoute();
const userStore = useUserStore();
const skyDialogRef = ref();
const formRef = ref();
const pageData = ref({
  props: {children: "child", label: "ProTypeName"},
  treeData: [],
  showSearch: true,
  searchParams: {
    keyWord: "",
    sort: "asc",
    manage: true,
  },
  productTypeParams: {
    ProTypeCode: "",
    ProTypeName: "",
  },
  pageParams: {
    pageIndex: 1,
    SortFields: "FProTypeCode",
    direction: "asc",
    pageSize: 10,
  },
  ids: [],
  single: true,
  multiple: true,
  title: "字典信息维护",
  confirmLoading: false,
  form: {
    TopProTypeCode: "",
    TopProTypeName: "",
    ProTypeCode: "",
    ProTypeName: "",
    ClassType: 0,
    BillDate: getNowDate(),
    IsValid: 1,
    Remark: "",
  },
  rules: {
    ProTypeCode: [{required: true, message: "请输入物料编号", trigger: "blur"}],
    ProTypeName: [{required: true, message: "请输入物料名称", trigger: "blur"}],
  },
  loading: false,
  total: 0,
  column: [],
  showTable: [
    {title: "物料编号", IsVisible: 1},
    {title: "物料名称", IsVisible: 1},
    {title: "类别属性", IsVisible: 1},
    {title: "上级类别名称", IsVisible: 1},
    {title: "有效码", IsVisible: 1},
    {title: "排序", IsVisible: 1},
    {title: "日期", IsVisible: 1},
    {title: "状态", IsVisible: 1},
    {title: "备注", IsVisible: 1},
  ],
  tableList: [],
});
const method = reactive({
  /** 物料类别树 */
  handleListTree: async () => {
    const data = apiParam("2.0", "PLM.ProductTypesDAL.GetProTypeTrees", [0]);
    try {
      pageData.value.treeData = [];
      const res = await productTypeApi(data);
      pageData.value.treeData = res.data;
    } catch (error) {
      skyMsgError("数据查询失败，请刷新重试🌻");
    }
  },
  /** 选择物料类别树 */
  handleCurrentChange: (val) => {
    pageData.value.productTypeParams.ProTypeCode = val.ProTypeCode;
    pageData.value.productTypeParams.ProTypeName = val.ProTypeName;
    method.handleListPage();
  },
  /** 关键字 */
  handleListKey: async () => {
    const data = apiParam("2.0", "PLM.ProductTypesDAL.Querybykeyvalue",
      [pageData.value.searchParams.keyWord, {
        pageNo: pageData.value.pageParams.pageIndex,
        ...pageData.value.pageParams
      }]);
    try {
      pageData.value.loading = true;
      pageData.value.tableList = [];
      const res = await productTypeApi(data);
      pageData.value.searchParams.keyWord = "";
      pageData.value.total = res.data.recordsTotal;
      pageData.value.tableList = res.data.data;
      pageData.value.loading = false;
    } catch (error) {
      skyMsgError("数据查询失败，请刷新重试🌻");
    }
  },
  /** 搜索 */
  handleSearch: () => {
    pageData.value.pageParams.pageIndex = 1;
    method.handleListKey();
  },
  /** 重置 */
  resetSearch: () => {
    method.resetSearchParams();
    method.handleListPage();
  },
  /** 重置搜索参数 */
  resetSearchParams: () => {
    pageData.value.searchParams = {
      keyWord: "",
      sort: "asc",
      manage: true,
    };
    pageData.value.productTypeParams = {
      ProTypeCode: "",
      ProTypeName: "",
    };
    pageData.value.pageParams = {
      pageIndex: 1,
      SortFields: "FProTypeCode",
      direction: "asc",
      pageSize: 10,
    };
  },
  /** 添加 */
  handleAdd: () => {
    // 打开弹出框
    skyDialogRef.value.skyOpen();
    // 重置表单
    method.resetForm();
    // 标题
    pageData.value.title = "添加";
    pageData.value.form.BillDate = getNowDate();
  },
  /** 来源类别 */
  handleChangeProductType: (val) => {
    pageData.value.form.TopProTypeCode = val.ProTypeCode;
    pageData.value.form.TopProTypeName = val.ProTypeName;
  },
  /** 删除 */
  handleDelete: (row) => {
    const id = row.RecordId;
    if (id === null || id === "") {
      skyMsgWarning("请选中需要删除的数据🌻");
      return;
    }
    skyMsgBox("您确认需要删除字典名称[" + row.ProTypeName + "]么？")
      .then(async () => {
        try {
          const data = apiParam("2.0", "PLM.ProductTypesDAL.Delete", [id]);
          await productTypeApi(data);
          await method.handleListTree();
          await method.handleListPage();
          skyNoticeSuccess("删除成功🌻");
        } catch (error) {
          await method.handleListPage();
          skyNoticeError("删除失败，请刷新重试🌻");
        }
      })
      .catch(() => {
        skyMsgError("已取消🌻");
      });
  },
  /** 批量删除 */
  handleBatchDelete: () => {
    return skyMsgInfo("暂不支持批量删除");
  },
  /** 修改 */
  handleUpdate: (row) => {
    // 打开弹出框
    skyDialogRef.value.skyOpen();
    // 重置表单
    method.resetForm();
    pageData.value.title = "修改";
    const id = row ? row.RecordId : pageData.value.ids[0];
    if (id == null || id === "") {
      skyMsgError("请选中需要修改的数据🌻");
    }
    // 回显数据
    method.handleEcho(id);
  },
  /** 回显数据 */
  handleEcho: async (id) => {
    if (id === null || id === "") {
      skyMsgWarning("请选择需要修改的数据🌻");
      return;
    }
    try {
      const data = apiParam("2.0", "PLM.ProductTypesDAL.GetById", [id]);
      const res = await productTypeApi(data);
      pageData.value.form = res.data;
    } catch (error) {
      skyNoticeError("数据获取失败，请刷新重试🌻");
    }
  },
  /** 确定  */
  handleConfirm: () => {
    if (!formRef.value) return;
    pageData.value.confirmLoading = true;
    (formRef.value).validate(async (valid) => {
      if (valid) {
        if (pageData.value.form.RecordId) {
          try {
            const data = apiParam("2.0", "PLM.ProductTypesDAL.Update",
              [pageData.value.form]);
            await productTypeApi(data);
            skyNoticeSuccess("修改成功🌻");
            pageData.value.confirmLoading = false;
            skyDialogRef.value.skyQuickClose();
            method.resetForm();
            await method.handleListTree();
            await method.handleListPage();
          } catch (error) {
            pageData.value.confirmLoading = false;
            skyNoticeError("修改失败，请刷新重试🌻");
          }
        } else {
          try {
            const data = apiParam("2.0", "PLM.ProductTypesDAL.Create",
              [pageData.value.form]);
            await productTypeApi(data);
            skyNoticeSuccess("添加成功🌻");
            pageData.value.confirmLoading = false;
            skyDialogRef.value.skyQuickClose();
            method.resetForm();
            await method.handleListTree();
            await method.handleListPage();
          } catch (error) {
            pageData.value.confirmLoading = false;
            skyNoticeError("添加失败，请刷新重试🌻");
          }
        }
      } else {
        skyMsgError("验证失败，请检查填写内容🌻");
        pageData.value.confirmLoading = false;
      }
    });
  },
  /** 取消 */
  handleCancel: () => {
    skyDialogRef.value.skyClose();
  },
  /** 清空表单数据 */
  resetForm: () => {
    nextTick(() => {
      if (formRef.value) {
        // 重置该表单项，将其值重置为初始值，并移除校验结果
        formRef.value.resetFields();
      }
    });
    pageData.value.form = {
      TopProTypeCode: "",
      TopProTypeName: "",
      ProTypeCode: "",
      ProTypeName: "",
      ClassType: 0,
      BillDate: getNowDate(),
      IsValid: 1,
      Remark: "",
    };
  },
  /** 导出 */
  handleDerive: () => {
    const column = [
      {title: "录入人", dataIndex: "Creator"},
      {title: "录入时间", dataIndex: "CreateTime"},
      {title: "修改人", dataIndex: "LastModifier"},
      {title: "修改时间", dataIndex: "LastModifyTime"},
    ];
    induce("物料分类报表", [...pageData.value.column, ...column], pageData.value.tableList);
    skyMsgSuccess("导出成功");
    method.handleListPage();
  },
  /** 是否多选 */
  handleSelectionChange: (selection) => {
    pageData.value.ids = selection.map((item) => item.RecordId);
    pageData.value.single = selection.length !== 1; // 单选
    pageData.value.multiple = !selection.length; // 多选
  },
  /** 表格表头 */
  handleListMeter: async () => {
    const data = apiParam("2.0", "SYS.UserColumnDefineDAL.Query",
      [{UserCode: userStore.userid, Context: route.path}]);
    try {
      const res = await productTypeApi(data);
      pageData.value.column = res.data.Columns.map(item => {
        return {
          title: item.DisplayCaption,
          dataIndex: item.DisplayFieldName,
        }
      });
    } catch (error) {
      skyMsgError("数据查询失败，请刷新重试🌻");
    }
  },
  /** 数据表格 */
  handleListPage: async () => {
    const data = apiParam("2.0", "PLM.ProductTypesDAL.Querybypage",
      [pageData.value.productTypeParams, pageData.value.pageParams]);
    try {
      pageData.value.loading = true;
      pageData.value.tableList = [];
      const res = await productTypeApi(data);
      pageData.value.total = res.data.recordsTotal;
      pageData.value.tableList = res.data.data;
      pageData.value.loading = false;
    } catch (error) {
      skyMsgError("数据查询失败，请刷新重试🌻");
    }
  },
});
onMounted(() => {
  method.handleListTree();
  method.handleListMeter();
  method.handleListPage();
});
</script>

<!-- 物料分类 -->
<template>
  <div class="sky-flex">
    <div class="treeList sky-flex">
      <SkyCard>
        <SkyTree
          tree-name="物料类别"
          :props="pageData.props"
          :treeData="pageData.treeData"
          node-key="ProTypeCode"
          @currentChange="method.handleCurrentChange"
        ></SkyTree>
      </SkyCard>
    </div>
    <div class="tableList sky-flex">
      <SkyCard>
        <!-- 搜索条件 -->
        <el-form v-show="pageData.showSearch" :inline="true">
          <el-form-item label="关键字" prop="keyWord">
            <el-input
              style="width: 240px"
              placeholder="请输入关键字"
              v-model="pageData.searchParams.keyWord"
              clearable
              @keyup.enter.native="method.handleListKey"
            ></el-input>
          </el-form-item>
          <el-form-item label="排序" prop="sort">
            <el-select v-model="pageData.searchParams.sort" style="width: 240px" clearable
                       @keyup.enter.native="method.handleListPage">
              <el-option label="升序" value="asc"/>
              <el-option label="降序" value="desc"/>
            </el-select>
          </el-form-item>
          <el-form-item label="是否显示管理字段" prop="manage">
            <el-checkbox v-model="pageData.searchParams.manage"/>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="search" plain v-throttle="method.handleSearch">搜索</el-button>
            <el-button type="danger" icon="refresh" plain v-debounce="method.resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
        <!-- 表格头部按钮 -->
        <el-row :gutter="10">
          <el-col :span="1.5">
            <el-button type="primary" icon="plus" plain @click="method.handleAdd()">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="delete" plain @click="method.handleBatchDelete()" :disabled="pageData.multiple">
              删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" icon="edit" plain @click="method.handleUpdate()" :disabled="pageData.single">修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" icon="download" plain @click="method.handleDerive">导出</el-button>
          </el-col>
          <SkyToolbar v-model:showSearch="pageData.showSearch" v-model:showColumns="pageData.showTable"
                      @refreshTable="method.handleListPage"></SkyToolbar>
        </el-row>
        <br/>
        <!-- 数据表格 -->
        <el-table
          v-loading="pageData.loading"
          border
          :data="pageData.tableList"
          empty-text="暂时没有数据哟🌻"
          @selection-change="method.handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column v-if="fieldVisible('物料编号', pageData.showTable)" label="物料编号" prop="ProTypeCode" width="150"
                           align="center" :show-overflow-tooltip="true"></el-table-column>
          <el-table-column v-if="fieldVisible('物料名称', pageData.showTable)" label="物料名称" prop="ProTypeName" width="150"
                           align="center" :show-overflow-tooltip="true"></el-table-column>
          <el-table-column v-if="fieldVisible('类别属性', pageData.showTable)" label="类别属性" prop="ClassType" width="150"
                           align="center" :show-overflow-tooltip="true">
            <template #default="scope">
              <el-tag v-if="!scope.row.ClassType" type="primary">目录</el-tag>
              <el-tag v-else type="success">明细</el-tag>
            </template>
          </el-table-column>
          <el-table-column v-if="fieldVisible('上级类别名称', pageData.showTable)" label="上级类别名称" prop="TopProTypeName"
                           width="150" align="center" :show-overflow-tooltip="true"></el-table-column>
          <el-table-column v-if="fieldVisible('有效码', pageData.showTable)" label="有效码" prop="IsValid" width="150"
                           align="center" :show-overflow-tooltip="true"></el-table-column>
          <el-table-column v-if="fieldVisible('日期', pageData.showTable)" label="日期" prop="BillDate" width="150" align="center"
                           :show-overflow-tooltip="true">
            <template #default="scope">
              {{ changeDateFormat(scope.row.BillDate, "YYYY-MM-DD") }}
            </template>
          </el-table-column>
          <el-table-column v-if="fieldVisible('状态', pageData.showTable)" label="状态" prop="State" width="120" align="center"
                           :show-overflow-tooltip="true">
            <template #default="scope">
              <SkyTag :tagOptions="stateOptions" :value="scope.row.State"></SkyTag>
            </template>
          </el-table-column>
          <el-table-column v-if="fieldVisible('备注', pageData.showTable)" label="备注" prop="Remark" width="180" align="center"
                           :show-overflow-tooltip="true"></el-table-column>
          <el-table-column v-if="pageData.searchParams.manage" label="录入人" prop="Creator" width="130"
                           align="center"></el-table-column>
          <el-table-column v-if="pageData.searchParams.manage" label="录入时间" prop="CreateTime" width="200" align="center"
                           :show-overflow-tooltip="true">
            <template #default="scope">
              {{ changeDateFormat(scope.row.CreateTime, "YYYY-MM-DD hh:mm:ss") }}
            </template>
          </el-table-column>
          <el-table-column v-if="pageData.searchParams.manage" label="修改人" prop="LastModifier" width="130"
                           align="center"></el-table-column>
          <el-table-column v-if="pageData.searchParams.manage" label="修改时间" prop="LastModifyTime" width="200" align="center"
                           :show-overflow-tooltip="true">
            <template #default="scope">
              {{ changeDateFormat(scope.row.LastModifyTime, "YYYY-MM-DD hh:mm:ss") }}
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="120" fixed="right">
            <template #default="{ row }">
              <el-tooltip content="修改🌻" placement="top">
                <el-button
                  type="primary"
                  icon="Edit"
                  circle
                  plain
                  @click="method.handleUpdate(row)"
                ></el-button>
              </el-tooltip>
              <el-tooltip content="删除🌻" placement="top">
                <el-button
                  type="danger"
                  icon="Delete"
                  circle
                  plain
                  @click="method.handleDelete(row)"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <br/>
        <!-- 分页 -->
        <el-pagination
          v-model:current-page="pageData.pageParams.pageIndex"
          v-model:page-size="pageData.pageParams.pageSize"
          v-show="pageData.total > 0"
          background
          :page-sizes="[10, 20, 50, 100, 200]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageData.total"
          @size-change="method.handleListPage"
          @current-change="method.handleListPage"
        />
        <!-- 添加 OR 修改 -->
        <SkyDialog
          ref="skyDialogRef"
          :title="pageData.title"
          @skyConfirm="method.handleConfirm"
          @skyCancel="method.handleCancel"
          :loading="pageData.confirmLoading"
          :width="1200"
          :height="500"
        >
          <template #content>
            <div class="sky-flex">
              <div class="formTree sky-flex">
                <SkyCard>
                  <SkyTree
                    tree-name="物料类别"
                    :props="pageData.props"
                    :treeData="pageData.treeData"
                    node-key="ProTypeCode"
                    @currentChange="method.handleChangeProductType"
                  ></SkyTree>
                </SkyCard>
              </div>
              <div class="form">
                <SkyCard>
                  <el-form ref="formRef" :rules="pageData.rules" :model="pageData.form" label-width="80px" status-icon>
                    <el-row>
                      <el-col :xs="{ span: 24 }" :sm="{ span: 12 }">
                        <el-form-item label="上级类别" prop="TopProTypeName">
                          <el-input v-model="pageData.form.TopProTypeName" placeholder="请输入上级类别" clearable/>
                        </el-form-item>
                      </el-col>
                      <el-col :xs="{ span: 24 }" :sm="{ span: 12 }">
                        <el-form-item label="上级编号" prop="TopProTypeCode" class="p-l-10px">
                          <el-input v-model="pageData.form.TopProTypeCode" placeholder="请输入上级编号" clearable/>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :xs="{ span: 24 }" :sm="{ span: 12 }">
                        <el-form-item label="物料编号" prop="ProTypeCode">
                          <el-input v-model="pageData.form.ProTypeCode" placeholder="请输入物料编号" clearable/>
                        </el-form-item>
                      </el-col>
                      <el-col :xs="{ span: 24 }" :sm="{ span: 12 }">
                        <el-form-item label="物料名称" prop="ProTypeName" class="p-l-10px">
                          <el-input v-model="pageData.form.ProTypeName" placeholder="请输入物料名称" clearable/>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :xs="{ span: 24 }" :sm="{ span: 12 }">
                        <el-form-item label="物料属性" prop="ClassType">
                          <el-select v-model="pageData.form.ClassType" clearable>
                            <el-option label="目录" :value="0"/>
                            <el-option label="明细" :value="1"/>
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col :xs="{ span: 24 }" :sm="{ span: 12 }">
                        <el-form-item label="日期" prop="BillDate" class="p-l-10px">
                          <el-date-picker style="width: 100%;" v-model="pageData.form.BillDate" type="date"
                                          placeholder="请选择日期"
                                          clearable/>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                        <el-form-item label="备注" prop="Remark">
                          <el-input v-model="pageData.form.Remark" :rows="5" type="textarea" placeholder="请输入备注"/>
                        </el-form-item>
                      </el-col>
                    </el-row>
                  </el-form>
                </SkyCard>
              </div>
            </div>
          </template>
        </SkyDialog>
      </SkyCard>
    </div>
  </div>
</template>

<style scoped lang="scss">
.sky-flex {
  flex-direction: row;

  .treeList {
    width: 18%;
  }

  .tableList {
    width: 82%;
  }

  .formTree {
    width: 23%;
  }

  .form {
    width: 77%;
  }
}
</style>
